package com.fise.localvideo.firstdemo;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.fise.localvideo.R;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


public class LocalVideoListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private static final String TAG = "LocalVideoListActivity";
    private static final int REQUEST_CODE = 1;

    private AsyncTask<Object, LocalVideoInfo, Void> mVideoUpdateTask;
    private List<LocalVideoInfo> mVideoList = new ArrayList<LocalVideoInfo>();
    ;
    private ListView mVideoListView;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_video_list);

        mVideoListView = findViewById(R.id.local_video_list_view);

        LocalVideoItemAdapter adapter = new LocalVideoItemAdapter(this, R.layout.local_video_list_items, mVideoList);
        mVideoListView.setAdapter(adapter);


        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        } else {
            mVideoUpdateTask = new VideoUpdateTask();
            mVideoUpdateTask.execute();

            //设置数据项被点击的监听器
            mVideoListView.setOnItemClickListener(this);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mVideoUpdateTask = new VideoUpdateTask();//异步加载资源列表
                mVideoUpdateTask.execute();//执行异步加载
            } else {
                Toast.makeText(this, "权限拒绝！", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if ((mVideoUpdateTask != null) &&
                (mVideoUpdateTask.getStatus() == AsyncTask.Status.RUNNING)) {
            mVideoUpdateTask.cancel(true);
        }

        mVideoUpdateTask = null;

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent();
        String path = mVideoList.get(position).getPath();
        String title = mVideoList.get(position).getName();
        Log.e("LocalVideo", "Url：" + path);
        Log.e("LocalVideo", "title：" + title);
        intent.putExtra("CHOOSE", path);
        Log.d(TAG, "  onItemClick 准备跳转播放： path:" + path + "    title:" + title);
      /*  intent.setClass(LocalVideoListActivity.this, VitamioActivity.class);
        startActivity(intent);*/

    }


    public class VideoUpdateTask extends AsyncTask<Object, LocalVideoInfo, Void> {

        //private Context context;
        //private List<LocalVideoInfo> mVideoList;
        @Override
        protected Void doInBackground(Object... objects) {


            Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

            String[] searchKey = new String[]{
                    MediaStore.Video.Media.TITLE, //对应文件的标题/名称
                    MediaStore.Images.Media.DATA, //对应文件的存放位置
                    MediaStore.Images.Media.DATE_ADDED, //对应文件的创建时间
                    MediaStore.Images.Media.DISPLAY_NAME, //文件显示的名称
                    MediaStore.Video.Media.DURATION      //文件显示总时长
            };
            String[] keywords = null;
            //String where = MediaStore.Video.Media.DATA + " like \"%"+"/Video"+"%\"";
            String sortOrder = MediaStore.Video.Media.DEFAULT_SORT_ORDER;

            ContentResolver resolver = getContentResolver();
            Cursor cursor = resolver.query(
                    uri,
                    searchKey,
                    //where,
                    null,
                    keywords,
                    sortOrder);

            if (cursor != null) {
                while (cursor.moveToNext() && !isCancelled()) {
                    //获取视频的存放路径
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                    //获取视频的标题
                    String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                    //获取视频的创建时间
                    String createdTime = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED));

                    String displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));  // //文件显示的名称
                    String displayDuration = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));   //  //文件显示总时长
                    //747334
                  String time=   convertDurationToTime(Float.valueOf(displayDuration));


                    Log.d(TAG,"  displayName:"+displayName+"   displayDuration:"+displayDuration+"    time:"+time);

                    //获取缩略图
                    //Bitmap thumb=ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
                    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);

                    //LocalVideoInfo info=new LocalVideoInfo(path,name,createdTime);
                    LocalVideoInfo info = new LocalVideoInfo(path, name, thumb, createdTime,displayName,time);
                    publishProgress(info);

                }

                cursor.close();
            }
            return null;
        }


        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
        }

        @Override
        protected void onProgressUpdate(LocalVideoInfo... values) {
            //super.onProgressUpdate(values);
            LocalVideoInfo info = values[0];
            mVideoList.add(info);
            LocalVideoItemAdapter adapter = (LocalVideoItemAdapter) mVideoListView.getAdapter();
            adapter.notifyDataSetChanged();

            Log.d(TAG, "  video信息：" + info.toString());

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    public static String convertDurationToTime(Float durationMs) {
        long seconds = (long) (durationMs / 1000 % 60);
        long minutes = (long) (durationMs / (1000 * 60) % 60);
        long hours = (long) (durationMs / (1000 * 60 * 60));

        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

}